package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {
    @Autowired
    public EmployeeService employeeService;

    @Autowired
    public HttpSession session;

    //这个项目post和put请求都是使用请求体传参的@RequestBody
    //@RequestBody只能标注在对象或者map之前
    @PostMapping("employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //接受请求参数
        String username = map.get("username");
        String password = map.get("password");
        //调用service进行登录
        ResultInfo resultInfo = employeeService.login(username,password);
        //登陆成功，将employye对象保存到session
        Employee employee = (Employee) resultInfo.getData();
        session.setAttribute("SESSION_EMPLOYEE", employee);
        //返回
        return resultInfo;
    }

    //退出
    @PostMapping("/employee/logout")
    public ResultInfo logout(){
        //注销用户session
        session.invalidate();
        return ResultInfo.success(null);
    }

    //员工查询
    @GetMapping("/employee/find")
    public ResultInfo findByName(String name){
        //调用service查询
        List<Employee> employeeList = employeeService.findByName(name);
        //返回结果
        return ResultInfo.success(employeeList);
    }

    //保存员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
        employeeService.save(employee);
        return ResultInfo.success(null);
    }

    //根据id查询员工信息
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    //更新用户
    @PutMapping
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }
}
